<?php
namespace mybackend\controllers\ext;

use common\support\AuthHelper;
use common\support\LogHelper;
use yii\log\Logger;
use yii\web\Controller;
use Yii;
use yii\web\Response;

/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2017/5/8
 * Time: 上午11:50
 */
class BaseSignController extends Controller
{
    public $enableCsrfValidation = false;
    private static $logger = null;

    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        $result = parent::beforeAction($action); // TODO: Change the autogenerated stub
        if (!$result) {
            return $result;
        }

        $requestURI = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "null";

        $this->log("request_uri:" . $requestURI . "post request_data:" . json_encode($_REQUEST));

        //必须检验签名  ts,sign
        $ts = \Yii::$app->request->request("ts");
        $sign = \Yii::$app->request->request("sign");

        //15分钟有效
        if (time() - $ts > 15 * 60) {
            $this->exportJson([], -1, "超时");
            return false;
        }

        //校验签名
        if (empty($sign)) {
            $this->exportJson([], -1, "校验失败");
            return false;
        }

        $params = \Yii::$app->request->request();
        //剔除 r 参数(包含url)
        unset($params["r"]);
        $genSign = AuthHelper::genSignWithSecret($params, \Yii::$app->params["ext-api-secret"]);

        if ($genSign != $sign) {
            $this->exportJson([], -1, "校验失败");
            return false;
        }

        return $result;
    }

    /**
     * 输出json格式数据
     * @param string|bool|array $data
     * @param bool $success
     */
    protected function json($data, $success = true)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if ($success === false) {
            Yii::$app->response->setStatusCode(500);
        }
        Yii::$app->response->data = $data;

        \Yii::$app->end();
    }

    /**
     * 输出json格式数据
     * @param string|bool|array $data 输出数据
     * @param string|int $retCode 自定义错误码
     * @param string $errMsg 错误信息
     * @param bool $sucess 是否设置500错误码
     */
    protected function exportJson($data = [], $retCode = 0, $errMsg = '', $sucess = true)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if ($sucess === false) {
            Yii::$app->response->setStatusCode(500);
        }
        $exportData['data'] = $data;
        $exportData['retCode'] = $retCode;
        $exportData['errMsg'] = $errMsg;
        Yii::$app->response->data = $exportData;

        \Yii::$app->end();
    }

    /**
     * log
     * @param $msg
     * @param int $logLevel
     */
    protected function log($msg, $logLevel = Logger::LEVEL_INFO)
    {
        if (!isset(self::$logger[$logLevel])) {
            $levelName = Logger::getLevelName($logLevel);
            $config = [
                'logFile' => Yii::$app->getRuntimePath() . '/logs/ext/' . $levelName . '.log',
            ];
            self::$logger[$logLevel] = new LogHelper($config);
        }
        self::$logger[$logLevel]->log($msg, $logLevel, "ext");
    }
}